package com.xudow.app.dynamicstate_old.data;

import android.content.Context;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.activeshare.edu.ucenter.common.messages.Message;
import com.activeshare.edu.ucenter.common.messages.user.UserDetailMessage;
import com.activeshare.edu.ucenter.models.base.Courses;
import com.activeshare.edu.ucenter.models.course.CourseWithOtherInfo;
import com.activeshare.edu.ucenter.models.user.UserCensus;
import com.baidu.platform.comapi.map.E;
import com.google.gson.Gson;
import com.jude.beam.model.AbsModel;
import com.xudow.app.XApplication;
import com.xudow.app.dynamicstate_old.data.server.DaggerServiceModelComponent;
import com.xudow.app.dynamicstate_old.data.server.ErrorTransform;
import com.xudow.app.dynamicstate_old.data.server.SchedulerTransform;
import com.xudow.app.dynamicstate_old.data.server.ServiceAPI;
import com.xudow.app.dynamicstate_old.domain.entity.AdvInfo;
import com.xudow.app.dynamicstate_old.domain.entity.AttentionType;
import com.xudow.app.dynamicstate_old.domain.entity.AttentionUser;
import com.xudow.app.dynamicstate_old.domain.entity.Dynamic;
import com.xudow.app.dynamicstate_old.domain.entity.DynamicComment;
import com.xudow.app.dynamicstate_old.domain.entity.DynamicFoward;
import com.xudow.app.dynamicstate_old.domain.entity.DynamicLike;
import com.xudow.app.dynamicstate_old.domain.entity.Grade;
import com.xudow.app.dynamicstate_old.domain.entity.Login;
import com.xudow.app.dynamicstate_old.domain.entity.PushMessage;
import com.xudow.app.dynamicstate_old.domain.entity.RecommendTalent;
import com.xudow.app.dynamicstate_old.domain.entity.UserCourseWithOtherInfo;
import com.xudow.app.dynamicstate_old.domain.entity.UserInfoVo;
import com.xudow.app.dynamicstate_old.domain.entity.UserIntroduce;
import com.xudow.app.dynamicstate_old.domain.entity.WrapUserIntroduce;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

import javax.inject.Inject;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import rx.Observable;

/**
 * Created by ske on 2016/6/10.
 */
public class DynamicModel extends AbsModel {

    @Inject
    ServiceAPI mServiceAPI;

    public static DynamicModel getInstance() {
        return getInstance(DynamicModel.class);
    }

    @Override
    protected void onAppCreate(Context ctx) {
        super.onAppCreate(ctx);
        DaggerServiceModelComponent.builder().build().inject(this);
    }

    public Observable<List<Grade>> loadGrades() {
        return mServiceAPI.loadGrades().compose(new SchedulerTransform<List<Grade>>());
    }

    public Observable<List<AttentionType>> loadInterest(String gradeIds) {
        return mServiceAPI.loadInterest(gradeIds).compose(new SchedulerTransform<List<AttentionType>>());
    }

    public Observable<List<Dynamic>> getDynamics(int limit, long time, int loadType) {
        if (loadType == 1) {
            return mServiceAPI.getDynamicsFirst(limit).compose(new SchedulerTransform<List<Dynamic>>());
        } else {
            return mServiceAPI.getDynamics(limit, time, loadType).compose(new SchedulerTransform<List<Dynamic>>());
        }

    }

    public Observable<Login> login(String username, String pwd, String umengToken) {
        return mServiceAPI.login(username, pwd, umengToken, 2).compose(new SchedulerTransform<Login>());
    }

    public Observable<UserDetailMessage> getUserInfo() {
        return mServiceAPI.getUserInfo().compose(new SchedulerTransform<UserDetailMessage>());
    }

    public Observable<Integer> like(long dynamicId, int userType) {
        return mServiceAPI.like(dynamicId, userType).compose(new SchedulerTransform<>());
    }

    public Observable<Integer> unLike(long dynamicId) {
        return mServiceAPI.unLike(dynamicId).compose(new SchedulerTransform<>());
    }

    public Observable<List<DynamicLike>> getLikeList(long dynamicId, int limit, long time, int loadType) {
        return mServiceAPI.getLikeList(dynamicId, limit, time, loadType).compose(new SchedulerTransform<List<DynamicLike>>());
    }

    public Observable<List<DynamicLike>> getLikeListFirst(long dynamicId, int limit) {
        return mServiceAPI.getLikeListFirst(dynamicId, limit).compose(new SchedulerTransform<List<DynamicLike>>());
    }

    public Observable<List<DynamicComment>> getDynamicCommentFirst(long dynamicId, int limit) {
        return mServiceAPI.getDynamicCommentFirst(dynamicId, limit).compose(new SchedulerTransform<List<DynamicComment>>());
    }

    public Observable<List<DynamicComment>> getDynamicComment(long dynamicId, int limit, long time, int loadType) {
        return mServiceAPI.getDynamicComment(dynamicId, limit, time, loadType).compose(new SchedulerTransform<List<DynamicComment>>());
    }

    public Observable<Integer> newDynamic(Dynamic dynamicJson, String attentions, String subjects) {
        JSONObject jsonObject = new JSONObject();
        try {
//            jsonObject.put("attentionTypeId", dynamicJson.getAttentionTypeId());
            jsonObject.put("content", dynamicJson.getContent());
            jsonObject.put("isprivate", dynamicJson.getIsprivate());
            jsonObject.put("type", dynamicJson.getType());
            jsonObject.put("usertype", dynamicJson.getUsertype());
            if (!TextUtils.isEmpty(dynamicJson.getImgpath()))
                jsonObject.put("imgpath", dynamicJson.getImgpath());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mServiceAPI.newDynamic(jsonObject.toString(), attentions, subjects).compose(new SchedulerTransform<Integer>());
    }

    public Observable<List<Dynamic>> discoverDynamics(Context context, int limit, long time, int loadType) {
        if (loadType == 1) {
            if (XApplication.getInstance().isLogin()) {
//                String attention = PreferenceManager.getDefaultSharedPreferences(XApplication.getInstance()).getString("attentiontype", "[]");
//                String grades = PreferenceManager.getDefaultSharedPreferences(context).getString("Grade", "[]");
                return mServiceAPI.discoverDynamicsFirst(limit).compose(new SchedulerTransform<List<Dynamic>>());
            } else {
//                String attention = PreferenceManager.getDefaultSharedPreferences(XApplication.getInstance()).getString("attentiontype", "[]");
//                AttentionType[] attentionTypes = new Gson().fromJson(attention, AttentionType[].class);
//                int[] data = new int[attentionTypes.length];
//                for (int i = 0; i < attentionTypes.length; i++) {
//                    data[i] = attentionTypes[i].getId();
//                }
                String attention = PreferenceManager.getDefaultSharedPreferences(XApplication.getInstance()).getString("attentiontype", "[]");
                String grades = PreferenceManager.getDefaultSharedPreferences(context).getString("Grade", "[]");
                return mServiceAPI.discoverDynamicsFirstNotLogin(limit, attention, grades).compose(new SchedulerTransform<List<Dynamic>>());
            }
        } else {
            if (XApplication.getInstance().isLogin()) {
                String attention = PreferenceManager.getDefaultSharedPreferences(XApplication.getInstance()).getString("attentiontype", "[]");
                String grades = PreferenceManager.getDefaultSharedPreferences(context).getString("Grade", "[]");
                return mServiceAPI.discoverDynamics(limit, time, loadType).compose(new SchedulerTransform<List<Dynamic>>());
            } else {
//                String attention = PreferenceManager.getDefaultSharedPreferences(XApplication.getInstance()).getString("attentiontype", "[]");
//                AttentionType[] attentionTypes = new Gson().fromJson(attention, AttentionType[].class);
//                int[] data = new int[attentionTypes.length];
//                for (int i = 0; i < attentionTypes.length; i++) {
//                    data[i] = attentionTypes[i].getId();
//                }
                String attention = PreferenceManager.getDefaultSharedPreferences(XApplication.getInstance()).getString("attentiontype", "[]");
                String gradeIds = PreferenceManager.getDefaultSharedPreferences(context).getString("Grade", "[]");
                return mServiceAPI.discoverDynamicsNotLogin(limit, time, loadType, attention, gradeIds).compose(new SchedulerTransform<List<Dynamic>>());
            }
        }
    }

    public Observable<List<Dynamic>> recommentDynamics(int limit, long time, int loadType) {
        if (loadType == 1)
            return mServiceAPI.recommentDynamicsFirst(limit).compose(new SchedulerTransform<List<Dynamic>>());
        else
            return mServiceAPI.recommentDynamics(limit, time, loadType).compose(new SchedulerTransform<List<Dynamic>>());
    }

    public Observable<Dynamic> getDynamicDetail(long id) {
        return mServiceAPI.getDynamicsDetail(id).compose(new SchedulerTransform<>());
    }

    public Observable<List<RecommendTalent>> getRecommentTalent(int page, int offset) {
        return mServiceAPI.getRecommentTalent(page, offset).compose(new SchedulerTransform<List<RecommendTalent>>());
    }

    public Observable<Message> attention(long attentionId, int a_usertype, int u_usertype) {
        return mServiceAPI.attention(attentionId, a_usertype, u_usertype).compose(new SchedulerTransform<Message>());
    }

    public Observable<WrapUserIntroduce> getUserIntroduce(long userId) {
        return mServiceAPI.getUserIntroduce(userId).compose(new SchedulerTransform<>()).compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST));
    }

    public Observable<WrapUserIntroduce> getAgencyInfo(long userId) {
        return mServiceAPI.getAgencyInfo(userId).compose(new SchedulerTransform<>()).compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST));
    }

    public Call<WrapUserIntroduce> getUserIntroduceLock(long userId) {
        return mServiceAPI.getUserIntroduceLock(userId);
    }

    public Observable<WrapUserIntroduce> getUserInfo(long userId) {
        return mServiceAPI.getUserInfo(userId).compose(new SchedulerTransform<>()).compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST));
    }

    public Observable<List<Dynamic>> getDynamicsForUserFirst(long userId, int limit) {
        return mServiceAPI.getDynamicsFroUserFirst(userId, limit).compose(new SchedulerTransform<List<Dynamic>>());
    }

    public Observable<List<Dynamic>> getDynamicsForUser(long userId, int limit, long time, int loadType) {
        return mServiceAPI.getDynamicsForUser(userId, limit, time, loadType).compose(new SchedulerTransform<List<Dynamic>>());
    }

    public Observable<List<UserCourseWithOtherInfo>> getCourseForUser(long userId, int page, int limit) {
        return mServiceAPI.getCourseForUser(userId, page, limit).compose(new SchedulerTransform<>());
    }

    public Observable<List<Courses>> getRecommentCourse(int page, int limit, double latitude, double longitude) {
        return mServiceAPI.getRecommentCourse(page, limit, latitude, longitude).compose(new SchedulerTransform<>());
    }

    public Observable<Message> setDinamicPrivate(long dynamic_id) {
        return mServiceAPI.setDynamicPrivate(dynamic_id).compose(new SchedulerTransform<Message>());
    }

    public Observable<Message> deleteDynamic(long dynamic_id) {
        return mServiceAPI.deleteDynamic(dynamic_id).compose(new SchedulerTransform<Message>());
    }

    public Observable<Message> unattention(long user_profile_id) {
        return mServiceAPI.unattention(user_profile_id).compose(new SchedulerTransform<Message>());
    }

    public Observable<Integer> collectDynamic(long dynamic_id) {
        return mServiceAPI.collectDynamic(dynamic_id).compose(new SchedulerTransform<>());
    }

    public Observable<Integer> unCollectDynamic(long dynamic_id) {
        return mServiceAPI.unCollectDynamic(dynamic_id).compose(new SchedulerTransform<>());
    }

    public Observable<Integer> commentDynamic(String commentJson) {
        return mServiceAPI.commentDynamic(commentJson).compose(new SchedulerTransform<Integer>());
    }

    public Observable<Integer> forwardDynamic(String dynamicJson, long dynamicId) {
        return mServiceAPI.forwardDynamic(dynamicJson, dynamicId).compose(new SchedulerTransform<>());
    }

    public Observable<List<DynamicFoward>> getDynamicFowardFirst(long dynamic_id, int limit) {
        return mServiceAPI.forwardList(dynamic_id, limit).compose(new SchedulerTransform<>());
    }

    public Observable<Integer> defriendUser(long user_profile_id) {
        return mServiceAPI.defriendUser(user_profile_id).compose(new SchedulerTransform<>());
    }

    public Observable<List<AttentionUser>> getAttentionUser(long userId, int limit, long time, int loadType) {
        return mServiceAPI.getAttentionUser(userId, limit, time, loadType).compose(new SchedulerTransform<List<AttentionUser>>());
    }

    public Observable<List<AttentionUser>> getAttentionUser(long userId, int limit) {
        return mServiceAPI.getAttentionUser(userId, limit).compose(new SchedulerTransform<List<AttentionUser>>());
    }

    public Observable<List<AttentionUser>> getFans(long userId, int limit, long time, int loadType) {
        return mServiceAPI.getFans(userId, limit, time, loadType).compose(new SchedulerTransform<List<AttentionUser>>());
    }

    public Observable<List<AttentionUser>> getFans(long userId, int limit) {
        return mServiceAPI.getFans(userId, limit).compose(new SchedulerTransform<List<AttentionUser>>());
    }

    public Observable<String> changeAvatar(String des, File file) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        MultipartBody.Part imageFileBody = MultipartBody.Part.createFormData("portrait", file.getName(), requestFile);

        RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), des);
        return mServiceAPI.changeAvatar(description, imageFileBody).compose(new SchedulerTransform<>());
    }

    public Observable<String> changeCover(String path) {
        return mServiceAPI.changeCover(path).compose(new SchedulerTransform<>());
    }

    public Observable<Message> uploadCertificate(String latestphoto, String certificate, int userType) {
        return mServiceAPI.uploadCertificate(latestphoto, certificate, userType).compose(new SchedulerTransform<Message>());
    }

    public Observable<Integer> submitUserRemark(long uid, String name) {
        return mServiceAPI.submitUserRemark(uid, name).compose(new SchedulerTransform<>());
    }

    public Observable<Integer> submitUserAttention(String grades, String attentions) {
        return mServiceAPI.submitUserAttention(grades, attentions).compose(new SchedulerTransform<>());
    }

    public Observable<List<UserInfoVo>> searchUser(String name, int page, int limit) {
        return mServiceAPI.searchUser(name, page, limit).compose(new SchedulerTransform<>());
    }

    public Observable<List<Dynamic>> searchDynamic(String content, long time, int type, int limit) {
        return mServiceAPI.searchDynamic(content, time, type, limit).compose(new SchedulerTransform<>());
    }

    public Observable<List<PushMessage>> getMsgList(long time, int type, int limit) {
        return mServiceAPI.getMsgList(time, type, limit).compose(new SchedulerTransform<>());
    }

    public Observable<Message> delMsg(long pid) {
        return mServiceAPI.delMsg(pid).compose(new SchedulerTransform<>());
    }

    public Observable<List<Dynamic>> getCollectDynamics(int limit, long time, int loadType) {
        return mServiceAPI.getCollectDynamics(limit, time, loadType).compose(new SchedulerTransform<>());
    }

    public Observable<Message> deleteComment(long dynamicId, long commentId) {
        return mServiceAPI.deleteComment(dynamicId, commentId).compose(new SchedulerTransform<>());
    }

    public Observable<List<PushMessage>> getSystemMsgs(long time, int type, int limit) {
        return mServiceAPI.getSystemMsgs(time, type, limit).compose(new SchedulerTransform<>());
    }

    public Observable<Message> clearSystemMsg() {
        return mServiceAPI.clearSystemMessage().compose(new SchedulerTransform<>());
    }

    public Observable<Message> clearUserMsg() {
        return mServiceAPI.clearUserMessage().compose(new SchedulerTransform<>());
    }

    public Observable<List<AttentionType>> getAttentionTypes() {
        return mServiceAPI.getAttentionTypes().compose(new SchedulerTransform<>()).compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST));
    }

    public Observable<List<AdvInfo>> getBanner(int appPage) {
        return mServiceAPI.getBanner(appPage).compose(new SchedulerTransform<>());
    }

    public Observable<Message> report(String reportJson) {
        return mServiceAPI.report(reportJson).compose(new SchedulerTransform<>()).compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST));
    }

    public Observable<Message> tagLike(long user_profile_id) {
        return mServiceAPI.tagLike(user_profile_id).compose(new SchedulerTransform<>()).compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST));
    }

    public Observable<Message> unTagLike(long user_profile_id) {
        return mServiceAPI.unTagLike(user_profile_id).compose(new SchedulerTransform<>()).compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST));
    }

    public Observable<List<UserCourseWithOtherInfo>> getCourseForUser(int page, int offset) {
        return mServiceAPI.getCourseForUser(offset, page).compose(new SchedulerTransform<>());
    }

    public Observable<UserCensus> getUserRecord(long userId) {
        return mServiceAPI.getUserRecord(userId).compose(new SchedulerTransform<>()).compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST));
    }

    public Observable<Message> shareCount(long courseId, int type) {
        return mServiceAPI.shareCount(courseId, type).compose(new SchedulerTransform<>());
    }

    public Observable<Message> readArticleCount(long dynamicId){
        return mServiceAPI.readArticleCount(dynamicId).compose(new SchedulerTransform<>());
    }
}